﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Mvc.Html;

namespace GeckoPhotos.Util.Extensions
{
    public static class ViewMasterPageExtensions
    {

        public static bool IsController(this ViewMasterPage vpm, string controller)
        {
            if (vpm.ViewContext.RouteData.Values["controller"] != null)
            {
                return vpm.ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);
            }
            return false;
        }

        public static bool IsController<TController>(this ViewMasterPage vpm) where TController : Controller
        {
            return typeof(TController) == vpm.ViewContext.Controller.GetType();
        }

        public static bool IsAction(this ViewMasterPage vpm, string action)
        {
            if (vpm.ViewContext.RouteData.Values["action"] != null)
            {
                return vpm.ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);
            }
            return false;
        }
        public static bool IsAction(this ViewMasterPage vpm, string action, string controller)
        {
            return vpm.IsController(controller) && vpm.IsAction(action);
        }

        public static bool IsAction<TController>(this ViewMasterPage vpm, LambdaExpression action) where TController : Controller
        {
            MethodCallExpression call = action.Body as MethodCallExpression;
            if (call == null)
                throw new ArgumentException("Expression must be a method call", "action");

            return IsAction(vpm, call.Method.Name) && IsController<TController>(vpm);
        }

        public static MvcHtmlString BuildMenuItem<TController>(this ViewMasterPage vpm, string text, Expression<Action<TController>> action) where TController : Controller
        {
            bool selected = IsAction<TController>(vpm, action);

            MethodCallExpression call = action.Body as MethodCallExpression;
            if (call == null)
                throw new ArgumentException("Expression must be a method call", "action");

            string actionName = call.Method.Name;

            string controllerName = typeof(TController).Name;
            controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length);

            object htmlAttributes = null;
            if (selected)
                htmlAttributes = new { @class = "current" };    // A bit smelly - this would change depending on the stylesheet being used so shouldn't be defined in this class

            return vpm.Html.ActionLink(text, actionName, controllerName, null, htmlAttributes);
        }

    }
}